package com.wl.dzt.sys.util;

import com.wl.dzt.sys.constant.CommConstant;
import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.util.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description web工具
 */
public class WebUtils {
    /**
     * 获取请求参数
     */
    public static Param getParam(HttpServletRequest request) {
        Object p = request.getAttribute("param");
        return p == null ? null : (Param) request.getAttribute("param");
    }

    /**
     * 获取登陆用户
     */
    public static <T> T getUser(HttpServletRequest request) {
        if (request.getSession() == null) {
            return null;
        }
        return (T) request.getSession().getAttribute(CommConstant.BACK_USER_INFO);
    }


    /**
     * 输出json
     */
    public static void json(Object object, HttpServletResponse response) {
        print(Json.parse(object), response);
    }

    /**
     * 输出
     */
    public static void print(String html, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter;
        try {
            printWriter = response.getWriter();
            printWriter.print(html);
            printWriter.flush();
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * <b>获取网站的根路径</b>
     * <p>
     * 获取网站的根路径
     * </p>
     *
     * @param request 请求
     * @return 网站根路径字符串
     */
    public static String getWebRootPath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("");
    }
}
